package com.ejd.utils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

public class SortManagerDelegate<T> {
	private List<T> datas = new ArrayList<T>();//need to sort datas

    private String sortByProperty = "";
    public List<T> getDatas(){
    	return this.datas;
    }
    public void setDatas(List<T> datas){
    	this.datas=datas;
    }
    public String getSortByProperty(){
    	return this.sortByProperty;
    }
    public void setSortByProperty(String sort){
    	this.sortByProperty=sort;
    }
   //升序排
    public SortManagerDelegate(){
    	
    }
    private transient final Comparator<T> propertyAscendingComparator = new Comparator<T>() {
            public int compare(Object object1, Object object2) {
                try {
                    String property1 = BeanUtils.getProperty(object1,
                            SortManagerDelegate.this.sortByProperty
                        );
                    String property2 = BeanUtils.getProperty(object2,
                            SortManagerDelegate.this.sortByProperty
                        );

                    return property1.toLowerCase().compareTo(property2.toLowerCase());
                } catch (Exception e) {
                    return 0;
                }
            }
        };

    //降序排
    private transient final Comparator<T> propertyDescendingComparator = new Comparator<T>() {
            public int compare(Object object1, Object object2) {
                try {
                    String property1 = BeanUtils.getProperty(object1,
                            SortManagerDelegate.this.sortByProperty
                        );
                    String property2 = BeanUtils.getProperty(object2,
                            SortManagerDelegate.this.sortByProperty
                        );

                    return property2.toLowerCase().compareTo(property1.toLowerCase());
                } catch (Exception e) {
                    return 0;
                }
            }
        };

  
   

   
    public List<T> findDec() {
  
        sort(propertyDescendingComparator);

        return datas;
    }

   
    public List<T> findAsc() {
        
        sort(propertyAscendingComparator);

        return datas;
    }


    private void sort(Comparator<T> comparator) {
        Collections.sort(datas, comparator);
    }
}
